package com.qunar.toku.proxy;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;

import com.qunar.toku.configuration.ServiceConfig;
import com.qunar.toku.loadbalance.Dispatcher;
import com.qunar.toku.loadbalance.Server;

public class ServiceProxy {
	private final InternalLogger logger = 
			InternalLoggerFactory.getInstance(ServiceProxy.class);
	private Dispatcher dispatcher;
	private ServiceConfig config;
	private static final Object locker = new Object();
	private static final HashMap<String, ServiceProxy> proxys = new HashMap<String, ServiceProxy>();

	private ServiceProxy(String serviceName) throws Exception {
		config = ServiceConfig.getConfig(serviceName);
		dispatcher = new Dispatcher(config);

	}

	public static ServiceProxy getProxy(String serviceName) throws Exception {
		ServiceProxy p = proxys.get(serviceName.toLowerCase());
		if (p == null) {
			synchronized (locker) {
				p = proxys.get(serviceName.toLowerCase());
				if (p == null) {
					p = new ServiceProxy(serviceName);
					proxys.put(serviceName.toLowerCase(), p);
				}
			}
		}
		return p;
	}

	public Future invoke(RequestProtocol protocol) throws Exception {

		Server server = dispatcher.getServer();

		if (server == null)
			throw new Exception("cannot get server");

		Future future = server.request(protocol);

		return future;
	}

	public static void destroyAll() {
		Collection<ServiceProxy> spList = proxys.values();
		if (spList != null) {
			for (ServiceProxy sp : spList) {
				sp.destroy();
			}
		}
	}
	
	private void destroy() {
    	List<Server> serverList = dispatcher.getAllServer();
		if(serverList != null) {
			for(Server server : serverList) {
				try {
					server.getSocketPool().destroy();
				} catch (Exception e) {
					logger.error("destory socketPool error" + e.getCause());
				}
			}
		}
    }
}
